package com.kg.elysia.controller;

import com.kg.elysia.service.AiService;
import com.kg.elysia.service.MuralService;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 *
 * </p>
 *
 * @author zj
 * @since 2025/10/21 20:03
 */
@Slf4j
public class AiController {

    private final Vertx vertx;

    private final AiService aiService;

    private final MuralService muralService;

    public AiController(Vertx vertx, MuralService muralService) {
        this.vertx = vertx;
        this.muralService = muralService;
        this.aiService = new AiService(vertx, muralService);
    }

    public void ask(RoutingContext ctx) {
        JsonObject body = ctx.getBodyAsJson();
        String question = null;
        if (body != null) {
            question = body.getString("question");
        }
        aiService.ask(question)
                .onSuccess(result -> ctx.response()
                        .putHeader("Content-Type", "application/json")
                        .end(result.encode()))
                .onFailure(err -> {
                    log.error("AI问答错误: ", err);
                    sendError(ctx, 500, "AI服务暂时不可用: " + err.getMessage());
                });
    }

    private void sendError(RoutingContext ctx, int statusCode, String message) {
        ctx.response()
                .setStatusCode(statusCode)
                .putHeader("Content-Type", "application/json")
                .end(new JsonObject().put("error", message).encode());
    }


}
